package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Pattern;

/*
* 美狐
* */
@Slf4j
public class Plugin_ECARD_P015 implements ChannelService {
    @Override
    public ChannelResult QueryBalance(JSONObject apiConfig) {
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }

    @Override
    public ChannelResult Submit(JSONObject apiConfig, Map<String, Object> data) {

        try {
            String AccountVal = String.valueOf(data.get("AccountVal"));


            LinkedHashMap<String, Object> params = new LinkedHashMap<>();

            params.put("product_id",Integer.valueOf(String.valueOf(data.get("SUPProductId"))));
            params.put("recharge_account",AccountVal);
            params.put("quantity",1);
            params.put("outer_order_id",String.valueOf(data.get("ChannelOrderCode")));
            //params.put("safe_cost",String.valueOf(data.get("PurchasePrice")));
            params.put("customer_id",Integer.valueOf(apiConfig.getString("partnerNumber")));
            params.put("timestamp",System.currentTimeMillis());
            //key:Mi7HYhY2SeUGJ5CiZhp8OeiQ0wFzyefelUk6ByLsOD1YqwDwkbl8nRFQ7txIeCkM
            String key=apiConfig.getString("pubKey"); //秘钥
            String sign = calculateSign(params, key); //签名
            params.put("sign",sign);
            String url = apiConfig.getString("SubmitURL"); //www.kashangwl.com/api/buy

            String result = HttpTool.sendPost2(url, params);

            JSONObject retobj = JSONObject.parseObject(result);
            log.info("响应参数"+JSON.toJSONString(retobj));
            String code = retobj.getString("code");
            String msg = retobj.getString("message");
            JSONObject dataParam = retobj.getJSONObject("data");
            if (code.equals("ok") ){ //成功状态
                //返回的第三方订单号保存-查询时需要使用
                String order_id = dataParam.getString("order_id");

                Integer state = dataParam.getInteger("state");
                if (state.equals(200) ) {
                    return  ChannelResult.success("充值成功");
                }
                if (state.equals(100)) {
                    return  ChannelResult.IN_PROCESS("充值中，等待发货");
                }
                if (state.equals(101)) {
                    return  ChannelResult.IN_PROCESS("充值中");
                }
            }
            if(code.equals("error") && msg.equals("外部订单号不能重复")){
                return  ChannelResult.IN_PROCESS("充值中");
            }
            if(code.equals("server_error")){
                return  ChannelResult.IN_PROCESS("未知错误，需人工核实");
            }
            return  ChannelResult.FAILED("下单失败:"+code+","+msg);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("美狐提交订单接口错误：",e);
            return  ChannelResult.error("美狐提交订单接口错误");
        }
    }

    @Override
    public ChannelResult Query(JSONObject apiConfig, Map<String, Object> data) {

        try {
            LinkedHashMap<String, Object> params = new LinkedHashMap<>();
            params.put("customer_id",Integer.valueOf(apiConfig.getString("partnerNumber")));
            params.put("outer_order_id",String.valueOf(data.get("ChannelOrderCode")));
            params.put("timestamp",System.currentTimeMillis());
            String key=apiConfig.getString("pubKey"); //秘钥
            String sign = calculateSign(params, key);

            params.put("sign",sign);
            String url = apiConfig.getString("QueryURL"); //www.kashangwl.com/api/outer-order

            String result = HttpTool.sendPost2(url, params);
            JSONObject retobj = JSONObject.parseObject(result);
            log.info("响应参数"+JSON.toJSONString(retobj));
            String code = retobj.getString("code");
            String msg = retobj.getString("message");
            JSONObject dataParam = retobj.getJSONObject("data");
            if (code.equals("ok") ){ //成功状态
                Integer state = dataParam.getInteger("state");
                if (state.equals(200) ) {
                    return  ChannelResult.success("充值成功");
                }
                if (state.equals(100)) {
                    return  ChannelResult.IN_PROCESS("充值成功，等待发货");
                }
                if (state.equals(101)) {
                    return  ChannelResult.IN_PROCESS("充值中");
                }
            }
            if(code.equals("server_error")){
                return  ChannelResult.IN_PROCESS("未知错误，需人工核实");
            }
            return  ChannelResult.FAILED(code+","+msg);

        }catch (Exception e) {
            e.printStackTrace();
            log.error("美狐查询订单接口错误：",e);
            return  ChannelResult.error("美狐查询订单接口错误");
        }

    }


    @Override
    public ChannelResult Notify(JSONObject apiConfig, Map<String, Object> data) {
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");
    }



    public static String calculateSign(Map<String, Object> params, String key) {
        // 将参数按照参数名的字典升序排列
        List<String> sortedKeys = new ArrayList<>(params.keySet());
        Collections.sort(sortedKeys);

        StringBuilder sb = new StringBuilder();
        sb.append(key);

        // 拼接参数名和参数值
        for (String paramName : sortedKeys) {
                sb.append(paramName);
                sb.append(params.get(paramName));
        }

       /* // 拼接时间戳
        sb.append("timestamp");
        sb.append(timestamp);*/

        // 计算 MD5
        return md5(sb.toString());
    }

    private static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());

            StringBuilder sb = new StringBuilder();
            for (byte b : messageDigest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            // 处理异常
            e.printStackTrace();
            return "";
        }
    }
}
